package lgq.xuan.httprequest;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;

import lgq.xuan.httprequest.param.BaseMsg;

public class MainActivity extends AppCompatActivity {

    private final String url = String.format("%s%s", BaseMsg.URI, BaseMsg.USER);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public static final String TAG = "resp-info";

    public void clickToSend(View send) {

        Map<String, String> param = new HashMap<>();

        EditText uidView = findViewById(R.id.input_name);
        String uid = uidView.getText().toString();
        param.put("uid", uid);

        EditText passView = findViewById(R.id.input_pass);
        String password = passView.getText().toString();
        param.put("password", password);

        jumpNet(param);

        BaseMsg.ONLINE = true;
    }

    JsonObjectRequest jsonObjectRequest;
    RequestQueue queue;

    public static final String LOGIN_UID = "login_uid";
    public static final String LOGIN_USERNAME = "login_username";
    public static final String LOGIN_PHONE = "login_phone";

    private final String USER_MESSAGE = "user_message.txt";

    private void jumpNet(Map<String, String> param) {
        queue = Volley.newRequestQueue(this);
        jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url + "/login", new JSONObject(param),
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {

                            int i = response.getInt("uid");

                            if (i <= 0) {
                                Toast.makeText(MainActivity.this, "用户名或密码错误", Toast.LENGTH_SHORT).show();
                                return;
                            }

                            String username = response.getString("username");
                            String phone = response.getString("phone");

                            userMsgSign(i, username);

                            Intent intent = new Intent(MainActivity.this, PhoneListActivity.class);
                            startActivity(intent);
                        } catch (JSONException | IOException e) {
                            e.printStackTrace();
                            Toast.makeText(MainActivity.this, "网络" + e.getMessage(), Toast.LENGTH_SHORT).show();
                        }

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e(TAG, "onErrorResponse: " + error.toString());
                    }
                });

        jsonObjectRequest.setTag(TAG);
        queue.add(jsonObjectRequest);
    }

    private void userMsgSign(int uid, String username) throws IOException {
        BaseMsg.UID = uid;

        File f = new File(this.getFilesDir(), USER_MESSAGE);
        if (!f.exists()) {
            f.createNewFile();
        }

        FileOutputStream ops = this.openFileOutput(USER_MESSAGE, Context.MODE_PRIVATE);
        try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(ops))) {
            bw.write("userId=" + uid + "\n");
            bw.write("username=" + username + "\n");
        }

        ops.close();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (queue != null) {
            queue.cancelAll(TAG);
        }
    }

    public void passLogin(View view) throws IOException {
        Intent intent = new Intent(this, PhoneListActivity.class);

        File f = new File(this.getFilesDir(), USER_MESSAGE);
        if (!f.exists()) {
            f.createNewFile();
        }

        FileInputStream inp = this.openFileInput(USER_MESSAGE);
        try (BufferedReader br = new BufferedReader(new InputStreamReader(inp))) {
            String line;
            while ((line = br.readLine()) != null) {
                String[] split = line.split("=");
                switch (split[0]) {
                    case "userId":
                        BaseMsg.UID = Integer.parseInt(split[1]);
                    case "username":
                        BaseMsg.USERNAME = split[1];
                }
                Log.i(TAG, "passLogin: " + line);
            }
        } catch (IOException e) {
            Log.e(TAG, "passLogin: " + e.getMessage());
        }
        inp.close();

        BaseMsg.ONLINE = false;

        startActivity(intent);
    }
}